package dao

import (
	"github.com/go-programming-tour-book/blog-service/internal/model"
	"time"
)

func (d *Dao) GetAddressList(userId uint32) ([]*model.UserAddress, error) {
	addr := model.UserAddress{UserId: userId}
	return addr.List(d.engine, 0, 0)
}

func (d *Dao) CountAddress(userId uint32) (int, error) {
	addr := model.UserAddress{UserId: userId}
	return addr.Count(d.engine)
}

func (d *Dao) GetAddress(id uint32) (model.UserAddress, error) {
	address := model.UserAddress{Model: &model.Model{ID: id}}
	return address.Get(d.engine)
}

func (d *Dao) CreateAddress(userId uint32, province, city, district, address, zip, contactName, contactPhone string) error {
	addr := model.UserAddress{
		Model: &model.Model{
			CreatedAt: "2021-05-25 23:30:00",
		},
		UserId:       userId,
		Province:     province,
		City:         city,
		District:     district,
		Address:      address,
		Zip:          zip,
		ContactName:  contactName,
		ContactPhone: contactPhone,
	}

	return addr.Create(d.engine)
}

func (d *Dao) UpdateAddress(id uint32, province, city, district, address, zip, contactName, contactPhone string) error {
	addr := model.UserAddress{
		Model: &model.Model{
			ID: id,
		},
	}
	values := map[string]interface{}{
		"province":      province,
		"city":          city,
		"district":      district,
		"address":       address,
		"zip":           zip,
		"contact_name":  contactName,
		"contact_phone": contactPhone,
		"modified_by":   time.Now().Unix(),
	}
	//if address != "" {
	//	values["address"] = address
	//}

	return addr.Update(d.engine, values)
}

func (d *Dao) DeleteAddress(id uint32) error {
	address := model.UserAddress{Model: &model.Model{ID: id}}
	return address.Delete(d.engine)
}
